<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;

class User extends Controller
{
    public function index()
    {
        // 原生SQL
        $sql = 'SELECT * FROM user';
        $list = Db::query($sql);

        // 预处理
        $sql = 'SELECT * FROM user WHERE id = ?';
        $list = Db::query($sql, [5]);

        // DB类
        $list = Db::table('user')->order(['id' => 'desc'])->select();

        // 助手函数
        $list = db('user')->order(['id' => 'asc'])->select();

        dump($list);
    }

    public function insert()
    {
        // 原生SQL
//        $sql = 'INSERT INTO user (id,name,age) VALUES (null,"k1",66)';
//        $result = Db::execute($sql);
        // 预处理
//        $sql = 'INSERT INTO user (id,name) VALUES (:id, :name)';
//        $result = Db::execute($sql, ['id'=>null, 'name'=>'k2']);

        $data = [
            'name' => 'k5',
            'age' => 99,
            'province' => '西安'
        ];
        // DB类   insertAll() 多条插入
//        $result = Db::table('user')->insert($data); // 受影响行数
//        $result = Db::table('user')->insertGetId($data); // 自增ID

        // 助手函数
        $result = db('user')->insert($data); // 受影响行数

        dump($result);
    }


    public function delete()
    {
        // 原生SQL
//        $sql = 'DELETE FROM user WHERE name="k2"';
//        $result = Db::execute($sql);
        // DB类
//        $result = Db::table('user')->delete(55);
//        $result = Db::table('user')->where('name','k1')->delete();

        // 助手函数
        $result = db('user')->delete(54);

        dump($result);
    }

    public function update()
    {
        // 原生SQL
//        $sql = 'UPDATE user SET age="5" WHERE id ="51"';
//        $result = Db::execute($sql);

        // DB类
//        $result = Db::table('user')->where(['id'=>51])->update(['age'=>88, 'sex'=>1]);

        // 助手函数
        $result = db('user')->where(['id'=>50])->update(['age'=>88, 'sex'=>1]);
        dump($result);

    }
}
